package club.weiyuanstudio.android.app.message_station.ui.message

import android.os.Bundle
import android.os.Handler
import android.util.Log
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import club.weiyuanstudio.android.app.message_station.R
import club.weiyuanstudio.android.app.message_station.api.MessageStationAPI
import club.weiyuanstudio.android.app.message_station.api.data.Message

/**
 * A fragment representing a list of Items.
 */
class MessageFragment : Fragment() {
    var UPDTE_MESSAGE_LIST = 1
    lateinit var recycleView: RecyclerView
    lateinit var refreshList: SwipeRefreshLayout
    var handler: Handler = object : Handler() {
        override fun handleMessage(msg: android.os.Message) {
            Log.d("Handle", this.toString())
            when (msg.what) {
                UPDTE_MESSAGE_LIST -> {
                    with(recycleView) {
                        layoutManager = LinearLayoutManager(context)
                        adapter =
                            MessageRecyclerViewAdapter(msg.obj as Array<Message>)
                    }
                    Toast.makeText(context, "Refresh Success", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_message_list, container, false)

        // Set the adapter
        recycleView = view.findViewById<RecyclerView>(R.id.recycleMessageList)
        if (view.findViewById<RecyclerView>(R.id.recycleMessageList) is RecyclerView) {
            with(recycleView) {
                layoutManager = LinearLayoutManager(context)
                adapter =
                    MessageRecyclerViewAdapter(arrayOf())
            }
        }

        AsyncMessageCall(this).start()

        refreshList = view.findViewById<SwipeRefreshLayout>(R.id.swipeRefreshMessageList)

        refreshList.setOnRefreshListener {
            AsyncMessageCall(this).start()
        }

        return view
    }

    inner class AsyncMessageCall(var messageFragment: MessageFragment) : Thread() {
        override fun run() {
            refreshList.isRefreshing = true

            val msg = android.os.Message()
            msg.what = UPDTE_MESSAGE_LIST
            msg.obj = MessageStationAPI().getMessageList()
            handler.sendMessage(msg)
            refreshList.isRefreshing = false
        }
    }
}
